package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.constants.SessionContents;
import com.example.demo.common.session.SessionComponent;
import com.example.demo.model.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author admin
 * @version 1.0.0
 * @time 2021/5/30 21:31
 * @desc TODO
 */
@RestController
@RequestMapping("/hello")
public class HelloController implements ApplicationListener<WebServerInitializedEvent> {

    @Autowired
    private SessionComponent sessionComponent;

    private int serverPort;

    @GetMapping("/tomcat/{userId}")
    public HttpResult tomcat(HttpServletRequest request, @PathVariable String userId) {
        String server = getHost() + ":" + serverPort;

        String sessionId = request.getHeader("sessionId");
        String username = sessionComponent.getSession(sessionId);

        JSONObject json = new JSONObject();
        json.put("server", server);
        json.put("username", username);

        return HttpResult.success(json);
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        serverPort = webServerInitializedEvent.getWebServer().getPort();
    }

    private String getHost() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address.getHostAddress();
    }
}
